package com.base.cn.platform.os.controller.user;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.rsa.WebRsaUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.controller.cmmon.ApiBaseController;
import com.base.cn.platform.os.service.course.agent.config.AgentConfigService;
import com.base.cn.platform.os.service.course.agent.user.AgentUserService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.member.CusUserMemberBuyRecordService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 用户信息接口Controller
 *
 * @author s.li
 * @create 2018-08-28-15:30
 */
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseController {

    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private AgentUserService agentUserService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private AgentConfigService agentConfigService;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    @Autowired
    private CusUserMemberBuyRecordService cusUserMemberBuyRecordService;

    /**
     * 获取用户信息
     * @param userId 用户ID
     * @return Map<String,Object>
     */
    @RequestMapping("/getUserInfo")
    public Map<String,Object> getUserInfo(@RequestParam("userId")BigDecimal userId){
        //获取用户信息
        Map<String,Object> userMap = cusUserService.userInfo(userId,false,false,false,false,false,false,false);
        if (ObjectUtils.isEmpty(userMap)){
            return ResultUtil.ERROR("请先登录!");
        }
        //获取用户是否推广员身份
        boolean isAgentUser = agentUserService.isAgentUser(userId);
        userMap.put("isAgentUser",isAgentUser);
        userMap.remove("password");
        userMap.remove("customerkey");
        Map<String, Object> stringObjectMap = agentConfigService.queryAgentConfigList();
        Map<String, Object> salesMap= (Map<String, Object>) stringObjectMap.get(ConfigName.SALES_INCOME);
        if(ObjectUtils.isNotEmpty(salesMap)){
            Map<String, Object> configMap = (Map<String, Object>) salesMap.get("configMap");
            userMap.put("explain", configMap.get("state"));
        }
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.SALE);
        String selaSwitch = configMap.get("selaSwitch");
        Map<String,Object> agentConfigMap = agentConfigService.queryAgentConfigList();
        Map<String,Object> agentUserConfig = (Map<String,Object>)((Map<String,Object>) agentConfigMap.get("AGENTCENTER")).get("configMap");
        String agentSwitch = (String)agentUserConfig.get("switch");
        Map<String,Object> resultMap = ResultUtil.SUCCESS(userMap);
        resultMap.put("selaSwitch",selaSwitch);
        resultMap.put("agentSwitch",agentSwitch);
        boolean isMemberUser =  cusUserMemberBuyRecordService.checkUserUseMemberPrice(userId);
        userMap.put("isMemberUser",isMemberUser);
        //定义开关
        userMap.put("switchState",dealSwitchValue()) ;
        return resultMap;
    }

    /**
     * 修改用户密码
     * @param userId 用户ID
     * @param nowPwd 原密码
     * @param newPwd 新密码
     * @param confirmPwd 确认新密码
     * @return Map<String,Object>
     */
    @RequestMapping("/updateUserPwd")
    public Map<String,Object> updateUserPwd(@RequestParam("userId") BigDecimal userId,
                                            @RequestParam("nowPwd") String nowPwd,
                                            @RequestParam("newPwd") String newPwd,
                                            @RequestParam("confirmPwd") String confirmPwd,
                                            @RequestParam(value = "rsaSign",required = false) String rsaSign) throws Exception{
        Map<String,Object> resultMap = cusUserService.updateUserPwd(userId,nowPwd,newPwd,confirmPwd,rsaSign);
        if(!ResultUtil.getSuccess(resultMap)){
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }
        return resultMap;
    }

    /**
     * 修改用户信息
     * @param userId 用户ID
     * @param nickname 用户昵称
     * @param realName 用户真实姓名
     * @param gender 性别
     * @param birthday 用户生日(yyyy-MM-dd)
     * @param userInfo 用户个性签名
     * @return Map<String,Object>
     */
    @RequestMapping("/updateUserInfo")
    public Map<String,Object> updateUserInfo(@RequestParam("userId") BigDecimal userId,
                                             @RequestParam(value = "nickname",required = false) String nickname,
                                             @RequestParam(value = "realName",required = false) String realName,
                                             @RequestParam(value = "gender",required = false) Integer gender,
                                             @RequestParam(value = "birthday",required = false) String birthday,
                                             @RequestParam(value = "userInfo",required = false) String userInfo) throws ParseException, UnsupportedEncodingException {
        Map<String,Object> user = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.isNotEmpty(birthday)){
            birthday = sdf.format(sdf.parse(birthday));
        }
        user.put("id",userId);
        user.put("nickname",nickname);
        user.put("realName",realName);
        user.put("gender",gender);
        user.put("birthday",birthday);
        if(StringUtils.isNotEmpty(userInfo)){
            user.put("userInfo", URLDecoder.decode(userInfo,"utf-8"));
        }
        Map<String,Object> resultMap = cusUserService.updateUser(user);
        ResultUtil.setEntity(resultMap,null);
        return resultMap;
    }

    /**
     * 保存用户修改的头像
     * @param userId 用户ID
     * @param avatar 头像路径
     * @return Map<String,Object>
     */
    @RequestMapping("/updateUserAvatar")
    public Map<String,Object> updateUserAvatar(@RequestParam("userId") BigDecimal userId,
                                               @RequestParam("avatar") String avatar){
        return cusUserService.saveUserAvatar(userId,avatar);
    }

    /**
     * 处理后台开关的值将字符串转为boolean
     */
    private Map<String,Boolean>  dealSwitchValue(){
        TreeMap<String, String> switchState = sysConfigService.getSysConfigContext(ConfigName.ONOFF);
        HashMap<String, Boolean> stringBooleanHashMap = new HashMap<>();
        if(ObjectUtils.isNotEmpty(switchState)){
            //ios收益提现开关
            String iosIncome = switchState.get("iosIncome");
            stringChangeBoolean("iosIncome",iosIncome,stringBooleanHashMap);
        }
        return stringBooleanHashMap;
    }

    /**
     * 处理开关数据
     * @param key
     * @param oldValue
     * @param data
     */
    private void stringChangeBoolean(String key,String oldValue, HashMap<String, Boolean> data){
    if(StringUtils.isEmpty(oldValue)){
                return;
      }
           boolean value =false;
            if(oldValue.equals("ON")){
                value =true;
            }
            data.put(key,value);
     }

}
